import { PageDto } from "../../models/page.model";
import { UaIpEntity } from "../../models/ua-ip.model";
import { TradeInfoTypeMap, TradeTypeMap, UaTradeEntity, UaTradeSearchDto } from "../../models/ua-trade.model";
import { GlobalService } from "../../services/global.service";
import { UaIpService } from "../../services/ua-ip.service";
import { UaTradeService } from "../../services/ua-trade.service";
import { formatTime, getUrlFromText } from "../../utils/util";

// pages/trade/trade.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    FILE_HOST: GlobalService.STATIC_ASSETS_HOST,
    SHOP: GlobalService.STATIC_FILE_HOST + '/marketing/shop-sm.png',
    ipList: [] as { label: string, value: number }[],
    ipLogoMap: {} as { [key: number]: string },
    tradeList: [] as UaTradeEntity[],
    TradeTypeMap: TradeTypeMap,
    TradeInfoTypeMap: TradeInfoTypeMap,
  },

  customData: {
    page: 1,
    totalPage: 1,
    searchRequest: {} as UaTradeSearchDto
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.setNavigationBarTitle({
      title: '集换广场'
    });
    this.getTabBar().setData({
      value: '/pages/trade/trade'
    });
    UaIpService.fetchUaIpList().then((response: UaIpEntity[]) => {
      const ipList: { label: string, value: number }[] = [];
      const ipLogoMap: { [key: number]: string } = {};
      for (const ip of response) {
        ipList.push({
          label: ip.ipTitleCn!,
          value: ip.id!
        });
        ipLogoMap[ip.id!] = ip.ipTitleLogo!;
      }
      this.setData({
        ipList,
        ipLogoMap,
      });
      this.load();
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.customData.page = 1;
    this.load();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.customData.page = 1;
    this.load();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.customData.page + 1 > this.customData.totalPage) {
      return;
    }
    this.customData.page++;
    this.load();
  },

  load() {
    UaTradeService.searchWithPage(this.customData.searchRequest, this.customData.page).then((response: PageDto<UaTradeEntity>) => {
      this.customData.totalPage = response.meta!.pageCount!;
      for (const item of response.data ?? []) {
        const date = new Date(item.updateDate ?? Date.now());
        item.updateDateStr = formatTime(date);
      }
      if (this.customData.page === 1) {
        this.setData({
          tradeList: response.data
        })
      } else {
        this.setData({
          tradeList: [...this.data.tradeList, ...response.data!]
        })
      }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onChoose(e: any) {
    const index = e.currentTarget.dataset['index'] as number;
    UaTradeService.hot(e.currentTarget.dataset['id']).then((result: boolean) => {
      if (result) {
        const attr = `tradeList[${index}].hot`
        this.setData({ [attr]: (this.data.tradeList[index].hot! + 1) })
      }
    });
    wx.setClipboardData({
      data: this.data.tradeList[index].link!,
      success() {
        wx.showToast({
          title: '链接复制成功',
        });
      }
    });

    const url = getUrlFromText(this.data.tradeList[index].link!);
    if (url && url.includes('https://m.tb.cn/')) {
      GlobalService.getGoofishItemId(url).then((response: any) => {
        if (response && response.id) {
          wx.navigateToMiniProgram({
            appId: 'wx9882f2a891880616',
            path: `pages/item-detail/index?id=${response.id}&formScene=home`
          });
        }
      })
    }
  },


  onReset(e: any) {
    this.customData.searchRequest = e.detail;
  },

  onSearch(e: any) {
    // console.log(e.detail)
    // this.setData({
    //   popupVisible: false
    // });
    this.customData.searchRequest = e.detail;
    this.onPullDownRefresh();
  },

  market() {
    // wx.navigateTo({
    //   url: `/pages/market/market.page?type=shop`
    // })

    wx.navigateToMiniProgram({
      appId: 'wx0495add712732b23',
      path: `wxa/pages/offlinePay/index?scene=SLF&mode=normal`
    });
  },
})